package service

import (
	"chat_demo/conf"
	"chat_demo/pkg/e"
	"encoding/json"
	"fmt"
	"github.com/gorilla/websocket"
	"go.mongodb.org/mongo-driver/mongo"
	"log"
)

var MongoDB *mongo.Database

func (manager *ClientManager) Start() {
	MongoDB = conf.MongoDBClient.Database(conf.MongoDBName)

	for {
		log.Println("<---监听管道通信--->")
		select {
		case conn := <-Manager.Register: // 建立连接
			log.Printf("建立新连接: %v", conn.ID)
			Manager.Clients[conn.ID] = conn
			replyMsg := &ReplyMsg{
				Code:    e.WebsocketSuccess,
				Content: "已连接至服务器",
			}
			msg, _ := json.Marshal(replyMsg)
			_ = conn.Conn.WriteMessage(websocket.TextMessage, msg)
		case conn := <-Manager.Unregister: // 断开连接
			log.Printf("连接失败:%v", conn.ID)
			if _, ok := Manager.Clients[conn.ID]; ok {
				replyMsg := &ReplyMsg{
					Code:    e.WebsocketEnd,
					Content: "连接已断开",
				}
				msg, _ := json.Marshal(replyMsg)
				_ = conn.Conn.WriteMessage(websocket.TextMessage, msg)
				close(conn.DataQueue)
				delete(Manager.Clients, conn.ID)
			}
			//广播信息
		case broadcast := <-Manager.Broadcast:
			var message Message
			err := json.Unmarshal(broadcast.Message, &message)
			if err != nil {
				fmt.Println("转换为目标结构体时出错:", err)
				return
			}
			chatRoom, err := ensureChatRoomExists(MongoDB.Collection("ChatRoom"), message.FormId, message.TargetId)
			if err != nil {
				fmt.Println("ensureChatRoomExists Err", err)
			}
			id := broadcast.Client.ID
			// 将 ObjectID 转换为字符串表示形式
			//chatRoomID := chatRoom.ID.Hex()
			SaveChatMessage(MongoDB, chatRoom.ID, id, message.Content)

			sendId := message.TargetId
			flag := false //默认对方不在线
			for id, conn := range Manager.Clients {
				if id != sendId {
					continue
				}
				select {
				case conn.DataQueue <- broadcast.Message:
					flag = true
				default:
					//意思是通道已经关闭?而此时还来不及关闭通道以及连接的一瞬间？
					close(conn.DataQueue)
					delete(Manager.Clients, conn.ID)
				}
			}
			//判断对方是否在线，在线就可以直接推送消息了
			if flag {
				log.Println("对方在线应答")
				replyMsg := &ReplyMsg{
					Code:    e.WebsocketOnlineReply,
					Content: "对方在线应答",
				}
				msg, err := json.Marshal(replyMsg)
				_ = broadcast.Client.Conn.WriteMessage(websocket.TextMessage, msg)
				//err = InsertMsg(conf.MongoDBName, id, string(message), 1, int64(3*month))
				if err != nil {
					fmt.Println("InsertOneMsg Err", err)
				}
			} else {
				log.Println("对方不在线")
				replyMsg := ReplyMsg{
					Code:    e.WebsocketOfflineReply,
					Content: "对方不在线应答",
				}
				msg, err := json.Marshal(replyMsg)
				_ = broadcast.Client.Conn.WriteMessage(websocket.TextMessage, msg)
				//err = InsertMsg(conf.MongoDBName, id, string(message), 0, int64(3*month))
				if err != nil {
					fmt.Println("InsertOneMsg Err", err)
				}
			}
			//SaveChatMessage(MongoDB.Collection("Message"), chatRoom.ID, id, message.Content)
		}
	}
}
